<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="id ? '编辑视图' : '添加视图'"
    width="500"
    :before-close="closeDialog"
  >
    <el-form ref="dataFormRef" :model="compData.dataForm" label-width="100px" :rules="formRules">
      <el-form-item v-if="!id && pid" label="父视图" prop="view_authority_text">
        <el-input disabled :value="ptext" autocomplete="off" />
      </el-form-item>
      <el-form-item label="视图名称" prop="view_authority_text">
        <el-input v-model="compData.dataForm.view_authority_text" :controls="false" :min="0" />
      </el-form-item>
      <el-form-item label="视图CODE" prop="view_name">
        <el-input v-model="compData.dataForm.view_name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="doSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ADD_VIEW, GET_VIEW, type IView, UPDATE_VIEW } from '@/api/view'
const emits = defineEmits(['close'])
const { id, pid, ptext } = defineProps(['id', 'pid', 'ptext'])
console.log(id)
const compData = reactive({
  dataForm: {
    view_authority_text: '',
    view_name: ''
  }
})
const getDetail = () => {
  GET_VIEW(id).then((res) => {
    console.log(res)
    const viewInfo = res.data
    const info = {
      view_authority_text: viewInfo.view_authority_text,
      view_name: viewInfo.view_name
    }
    compData.dataForm = info
  })
}
if (id) {
  getDetail()
}
const dialogFormVisible = ref(true)
const dataFormRef = ref()
const formRules = reactive({
  view_authority_pid: [{ required: true, message: '请选择父级视图', trigger: 'blur' }],
  view_authority_text: [{ required: true, message: '请输入视图名称', trigger: 'change' }],
  view_name: [{ required: true, message: '请输入视图CODE', trigger: 'blur' }]
})
const closeDialog = () => {
  emits('close')
}

//提交
const doSubmit = () => {
  console.log('doSubmit')
  dataFormRef.value.validate((valid: boolean) => {
    console.log(pid, 'pid')
    if (valid) {
      let params: IView = {
        view_authority_pid: pid,
        view_authority_text: compData.dataForm.view_authority_text,
        view_name: compData.dataForm.view_name
      }
      if (id) {
        params.id = id
        UPDATE_VIEW(params).then(() => {
          emits('close', true)
        })
      } else {
        ADD_VIEW(params).then((res) => {
          console.log(res)
          emits('close', true)
        })
      }
    }
  })
}
</script>

<style></style>
